/*
 * Copyright (c) 2025 GuoKaiHong (Shenzhen) Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "napi/native_api.h"
#include <aki/jsbind.h>
#include <string>
#include <usb/usb_ddk_api.h>
#include <usb/usb_ddk_types.h>
#include <unistd.h>
#include "gkh_log.h"
#include "QR_Encode.h"
#include <map>
#include <unordered_map>
#include <vector>
#include "constants.h"

static int g_deviceId;
static struct UsbDeviceDescriptor devDesc;

uint64_t g_devHandle = 0;
uint64_t g_interfaceHandle = 0;
uint8_t g_dataEp = 0;
uint8_t g_interface = 0;
uint16_t g_maxPktSize = 0;

UsbDeviceMemMap *devMmap = nullptr;

CQR_Encode* pQR_Encode = nullptr;

int g_rotationMode = 0;
int g_printerCommandMode = 0;

pthread_mutex_t g_mutexLock;

// 定义USB端点方向常量
#define USB_ENDPOINT_DIR_MASK 0x80         // 端点方向位掩码
#define USB_ENDPOINT_DIR_OUT 0x00          // 输出端点
#define USB_ENDPOINT_DIR_IN 0x80           // 输入端点

// 定义USB传输类型常量
#define USB_ENDPOINT_TYPE_MASK 0x03        // 传输类型位掩码
#define USB_ENDPOINT_TYPE_CONTROL 0x00     // 控制传输
#define USB_ENDPOINT_TYPE_ISOCHRONOUS 0x01 // 同步传输
#define USB_ENDPOINT_TYPE_BULK 0x02        // 批量传输
#define USB_ENDPOINT_TYPE_INTERRUPT 0x03   // 中断传输

// 将宏定义改为函数
static bool IsBulkEp(const struct UsbEndpointDescriptor &epDesc)
{
    return (((epDesc.bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT) &&
            (epDesc.bmAttributes & USB_ENDPOINT_TYPE_MASK) == USB_ENDPOINT_TYPE_BULK);
}

static bool IsIntIn(const struct UsbEndpointDescriptor &epDesc)
{
    return (((epDesc.bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_IN) &&
            ((epDesc.bmAttributes & USB_ENDPOINT_TYPE_MASK) == USB_ENDPOINT_TYPE_INTERRUPT));
}

// 辅助函数：在接口设置中查找批量端点
static std::tuple<bool, uint8_t, uint8_t, uint16_t>FindBulkEndpoint(
    struct UsbDdkInterfaceDescriptor *intDesc, uint32_t numSetting)
{
    const uint32_t maxEndpoints = 16; // 端点数量上限
    
    for (uint32_t setIdx = 0; setIdx < numSetting; ++setIdx) {
        uint32_t numEp = intDesc[setIdx].interfaceDescriptor.bNumEndpoints;
        struct UsbDdkEndpointDescriptor *epDesc = intDesc[setIdx].endPoint;
        
        // 验证端点数量在合理范围内
        if (numEp == 0 || numEp > maxEndpoints || !epDesc) {
            continue;
        }
        
        // 查找批量端点
        for (uint32_t epIdx = 0; epIdx < numEp; ++epIdx) {
            if (IsBulkEp((epDesc[epIdx].endpointDescriptor))) {
                return {true, intDesc[setIdx].interfaceDescriptor.bInterfaceNumber,
                        epDesc[epIdx].endpointDescriptor.bEndpointAddress,
                        epDesc[epIdx].endpointDescriptor.wMaxPacketSize};
            }
        }
    }
    
    return {false, {}, {}, {}};
}

// 获取手写板的接口和端点
static std::tuple<bool, uint8_t, uint8_t, uint16_t>GetInterfaceAndEndpoint(
    const struct UsbDdkConfigDescriptor *config)
{
    // 检查配置描述符是否有效
    if (!config) {
        return {false, {}, {}, {}};
    }
    // 定义常量替代魔法数字
    const uint32_t maxInterfaces = 255;  // USB接口数量上限
    const uint32_t minInterfaces = 0;    // 接口最小数量
    uint32_t numInterfaces = config->configDescriptor.bNumInterfaces;
    
    if (numInterfaces == minInterfaces || numInterfaces > maxInterfaces) {
        return {false, {}, {}, {}};
    }
    // 遍历接口
    for (uint32_t intIdx = 0; intIdx < numInterfaces; ++intIdx) {
        struct UsbDdkInterfaceDescriptor *intDesc = config->interface[intIdx].altsetting;
        uint32_t numSetting = config->interface[intIdx].numAltsetting;
        // 检查接口描述符和设置数量
        if (!intDesc || numSetting == minInterfaces || numSetting > maxInterfaces) {
            continue;
        }
        // 提取查找端点的逻辑到单独的函数中
        auto result = FindBulkEndpoint(intDesc, numSetting);
        if (std::get<0>(result)) {
            return result;
        }
    }
    return {false, {}, {}, {}};
}


/**
 * 初始化打印机设备
 * @param devid 设备ID，用于标识特定的打印机设备
 * 此函数负责初始化打印机设备，包括设置设备ID、初始化USB接口、获取设备描述符、
 * 配置描述符、接口和端点信息，并占用设备接口以供应用层使用。
 */
void Init(int devid)
{
    // 设置设备ID
    g_deviceId = devid;
    // 打印机设备初始化日志
    LOG("printer Init deviceid %{public}d", devid);
    LOG("printer Init deviceid %{public}d", g_deviceId);
    int ret;
    // 初始化USB接口
    ret = OH_Usb_Init();
    LOG("OH_Usb_Init ret %{public}d", ret);
    // 定义常量替代魔法数字
    const uint32_t deviceIdBusShift = 16;
    const uint32_t deviceIdBusMask = 0xFFFF0000;
    const uint32_t deviceIdDeviceMask = 0xFFFF;
    const int defaultConfigIndex = 1; // USB默认配置索引
    const int number32 = 32;
    // 获取设备描述符
    uint32_t busNum = ((g_deviceId & deviceIdBusMask) >> deviceIdBusShift);
    uint32_t deviceNum = g_deviceId & deviceIdDeviceMask;
    g_devHandle = (static_cast<uint64_t>(busNum) << number32) | deviceNum;
    // 获取设备描述信息
    ret = OH_Usb_GetDeviceDescriptor(g_devHandle, &devDesc);
    LOG("OH_Usb_GetDeviceDescriptor ret %{public}d %{public}d %{public}d", ret, devDesc.idProduct, devDesc.idVendor);
    struct UsbDdkConfigDescriptor *config = nullptr;
    // 获取配置描述符
    ret = OH_Usb_GetConfigDescriptor(g_devHandle, defaultConfigIndex, &config);
    LOG("OH_Usb_GetConfigDescriptor ret %{public}d", ret);
    // 解析接口和端点信息
    auto [res, interface, endpoint, maxPktSize] = GetInterfaceAndEndpoint(config);
    LOG("GetInterfaceAndEndpoint ret %{public}d", res);
    // 释放配置描述符资源
    OH_Usb_FreeConfigDescriptor(config);
    // 设置数据端点、最大包大小和接口信息
    g_dataEp = endpoint;
    g_maxPktSize = maxPktSize;
    g_interface = interface;
    // 占用接口，同时也会卸载内核键盘驱动
    ret = OH_Usb_ClaimInterface(g_devHandle, g_interface, &g_interfaceHandle);
    LOG("OH_Usb_ClaimInterface ret %{public}d g_interfacehandle:%{public}ld", ret, g_interfaceHandle);
}

std::map<std::string, std::vector<unsigned char>> usbCommands1 = {
    {"CMD1", {0x1b, 0x61, 0x00, 0xe7}},
    {"CMD2", {0x1c, 0x21, 0x0c, 0xe7}},
    {"CMD3", {0x1b, 0x21, 0x30, 0xe7}},
    {"CMD4", {0x1b, 0x47, 0x00, 0xe7}},
    {"CMD5", {0x31, 0x00}},
    {"CMD6", {0x0a, 0x31}},
    {"CMD7", {0x1b, 0x4a, 0xc8, 0xe7}},
    {"CMD8", {0x1b, 0x69, 0xe7}}
};
std::map<std::string, std::vector<unsigned char>> usbCommands = {
    {"CMD1", {0x1b, 0x61, 0x00, 0x95}},
    {"CMD2", {0x1c, 0x21, 0x0c, 0x95}},
    {"CMD3", {0x1b, 0x21, 0x30, 0x95}},
    {"CMD4", {0x1b, 0x47, 0x00, 0x95}},
    {"CMD5", {0x31, 0x00}},
    {"CMD6", {0x0a, 0x31}},
    {"CMD7", {0x1b, 0x4a, 0xc8, 0x95}},
    {"CMD8", {0x1b, 0x69, 0x95}},
    {"CMD9", {0x1b, 0x4c, 0x01, 0x95}},
};
std::map<std::string, std::vector<unsigned char>> usbCommands2 = {
    {"CMD1", {0x1B, 0x69}},
};

/**
 * UsbWrite函数用于向USB设备写入数据。
 * @param data 要写入的数据数组。
 * @param len 要写入的数据长度。
 * @return 返回写入操作的结果，成功与否。
 * 此函数首先会创建一个设备内存映射，然后将数据复制到映射的地址中，
 * 并通过USB管道发送请求将数据传输到USB设备。
 */
int UsbWrite(char data[], int length)
{
    // 定义常量替代魔法数字
    const uint32_t bufferExtraSize = 1;              // 为终止符预留的空间
    const uint32_t usbRequestTimeoutMs = 3000;       // USB请求超时时间(毫秒)
    const unsigned char terminatorByte = 0x03;        // 数据终止符字节
    const int logBufferMultiplier = 5;                // 日志缓冲区倍数
    const int hexStringLength = 5;                    // 每个字节转换为十六进制字符串的长度(" 0xXX")
    const int maxLogBufferSize = 1024;                // 日志缓冲区最大大小，防止过大分配
    const int count0 = 0;
    
    // 创建用于存放数据的缓冲区，长度为传入数据长度+1（为终止符预留空间）
    uint32_t ret = OH_Usb_CreateDeviceMemMap(g_devHandle, length + bufferExtraSize, &devMmap);
    if (ret != count0) {
        LOG("OH_Usb_CreateDeviceMemMap failed with ret:%{public}d", ret);
        return ret;
    }
    // 清空缓冲区
    memset(devMmap->address, count0, devMmap->bufferLength);
    // 使用memcpy将数据复制到缓冲区中（修复：应该使用length而不是bufferLength）
    memcpy(devMmap->address, data, length);
    // 日志打印
    int printLen = (length < devMmap->bufferLength) ? length : devMmap->bufferLength; // 实际要打印的字节数
    int strBufLen = printLen * logBufferMultiplier + bufferExtraSize;
    // 限制日志缓冲区大小以防止内存溢出
    if (strBufLen > maxLogBufferSize) {
        strBufLen = maxLogBufferSize;
        printLen = (strBufLen - bufferExtraSize) / logBufferMultiplier;
    }
    char *str = (char *)malloc(strBufLen);
    if (str != nullptr) {
        memset(str, count0, strBufLen);
        unsigned char *a = devMmap->address;
        for (int i = count0; i < printLen; i++) {
            sprintf(str + logBufferMultiplier * i, " 0x%02x", *a);
            a++;
        }
        LOG("usb_read :%{public}s \n", str);
        free(str); // 释放之前分配的内存
    }
    // 在数据末尾添加终止符，解决乱码问题
    devMmap->address[length] = terminatorByte;
    // 设置已传输数据的长度
    devMmap->transferedLength = length;
    // 日志输出，记录缓冲区中的数据
    LOG("*******************************************devMmap->address 2 %{public}s", devMmap->address);
    // 初始化USB请求管道
    struct UsbRequestPipe pipe;
    pipe.interfaceHandle = g_interfaceHandle;
    // 根据配置描述符找到所要通信的端点
    pipe.endpoint = g_dataEp;
    // 设置请求超时时间
    pipe.timeout = usbRequestTimeoutMs;
    // 日志输出，记录创建设备内存映射的结果
    LOG("start OH_Usb_SendPipeRequest. %{public}d", ret);
    // 发送USB管道请求
    ret = OH_Usb_SendPipeRequest(&pipe, devMmap);
    // 日志输出，记录发送管道请求的结果
    LOG("OH_Usb_CreateDeviceMemMap ret:%{public}d", ret);

    // 日志输出，记录缓冲区长度、大小、偏移量和已传输长度
    LOG("*******************************************devMmap->bufferLength %{public}d", devMmap->bufferLength);
    LOG("*******************************************devMmap->size %{public}d", (int)devMmap->size);
    LOG("*******************************************devMmap->offset %{public}d", devMmap->offset);
    LOG("*******************************************devMmap->transferedLength %{public}d", devMmap->transferedLength);
    // 释放设备内存映射
    OH_Usb_DestroyDeviceMemMap(devMmap);
    // 日志输出，记录释放设备内存映射的结果
    LOG("OH_Usb_DestroyDeviceMemMap %{public}d", ret);
    // 返回发送管道请求的结果
    return ret;
}

/**
 * 执行打印机自检命令
 * 该函数向打印机发送自检指令，使打印机打印出自检页。
 * 自检页通常包含打印机状态、配置信息和测试图案等内容。
 */
void SelfCheck()
{
    // 定义自检命令数据包
    const int selfCheckSize = 7;
    char selfCheckCommand[selfCheckSize];
    
    // 定义命令字节常量
    const char commandPrefix1 = 0x1D;
    const char commandPrefix2 = 0x28;
    const char commandType = 0x41;
    const char dataLengthLow = 0x02;
    const char dataLengthHigh = 0x00;
    const char selfCheckMode1 = 0x00;
    const char selfCheckMode2 = 0x02;
    
    // 构造自检命令数据包
    int index = 0;
    selfCheckCommand[index++] = commandPrefix1;
    selfCheckCommand[index++] = commandPrefix2;
    selfCheckCommand[index++] = commandType;
    selfCheckCommand[index++] = dataLengthLow;
    selfCheckCommand[index++] = dataLengthHigh;
    selfCheckCommand[index++] = selfCheckMode1;
    selfCheckCommand[index++] = selfCheckMode2;

    // 打印自检数据包的大小，用于调试或日志记录
    LOG("SelfCheck data size %{public}d", selfCheckSize);

    // 调用PRwrite函数发送自检命令数据包
    UsbWrite(selfCheckCommand, selfCheckSize);
}

/**
 * @brief 生成并打印QR码的测试函数
 * 本函数用于测试打印机的QR码生成功能。它会构造一个包含起始字符的数据包，
 * 并通过PRwrite函数发送给打印机执行打印操作。
 * @note 当前实现仅发送一个起始字符作为示例，实际应用中应包含完整的QR码数据
 */
void QrTest()
{
    // 定义起始字符常量，使用小驼峰命名法
    const char qrStartCommand = 0x02;
    
    // 初始化字符数组用于构造和发送数据
    char bSend[1];
    
    // 初始化索引变量，用于追踪数组中的当前位置
    int index = 0;
    
    // 向数组中写入起始字符，标志着QR码数据包的开始
    bSend[index++] = qrStartCommand;
    
    // 发送构造的数据包到打印机
    UsbWrite(bSend, sizeof(bSend));
}

/**
 * 关闭设备接口
 * 该函数用于释放之前打开的USB设备接口。它首先检查全局句柄是否已初始化，
 * 如果未初始化，则记录错误并返回错误码。如果句柄有效，则调用USB库函数
 * 来释放接口，并在完成后释放USB库本身。
 * @return 返回释放接口操作的结果代码
 * -1: 句柄未初始化或释放接口失败
 * 其他: 释放接口函数的返回值
 */
int SetClose()
{
    const int errorCode = -1;
    
    // 检查全局句柄是否已初始化
    if (g_devHandle == 0 || g_interfaceHandle == 0) {
        LOG("g_devHandle:0 or g_interfaceHandle:0");
        return errorCode;
    }
    
    // 释放接口
    int ret = OH_Usb_ReleaseInterface(g_interfaceHandle);
    
    // 释放USB DDK
    OH_Usb_Release();
    
    LOG("SetClose OH_Usb_ReleaseInterface ret : %{public}d.", ret);
    return ret;
}

/**
 * 执行打印机自检并打印自检页
 * 该函数通过向打印机发送特定的指令序列来触发自检打印功能
 * 它首先构造了一条指令消息，然后通过调用PRwrite函数将这条消息发送给打印机
 * @return 返回PRwrite函数的返回值，表示打印操作的结果
 */
int PrintSelfCheck()
{
    int iRes = 1;
    try {
        // 定义自检命令常量，使用小驼峰命名法
        const char selfCheckPrefix1 = 0x1D;
        const char selfCheckPrefix2 = 0x28;
        const char selfCheckCmdType = 0x41;
        const char dataLengthLow = 0x02;
        const char dataLengthHigh = 0x00;
        const char modeParam1 = 0x00;
        const char modeParam2 = 0x02;
        
        // 构造打印机自检指令的消息体
        const int selfCheckCmdSize = 7;
        char bSend[selfCheckCmdSize];
        int iIndex = 0;
        
        bSend[iIndex++] = selfCheckPrefix1;
        bSend[iIndex++] = selfCheckPrefix2;
        bSend[iIndex++] = selfCheckCmdType;
        bSend[iIndex++] = dataLengthLow;
        bSend[iIndex++] = dataLengthHigh;
        bSend[iIndex++] = modeParam1;
        bSend[iIndex++] = modeParam2;
        
        // 日志记录：打印自检数据的大小
        LOG("PrintSelfCheck data size %{public}d", selfCheckCmdSize);
        
        // 调用PRwrite函数将自检指令发送给打印机
        iRes = UsbWrite(bSend, selfCheckCmdSize);
    } catch (...) {
        // 异常处理：捕获所有异常，但在此函数中不进行任何处理
        LOG("指令发送失败");
    }
    return iRes;
}

/**
 * 设置清洁模式
 * 本函数通过发送特定的指令序列来启动清洁模式它构造了一个包含控制指令的字节数组，
 * 并使用PRwrite函数发送这个数组来执行清洁操作函数执行完毕后，会返回一个状态码，
 * 以指示操作是否成功
 * @return int 返回0表示成功，非零表示失败
 */
int SetClean()
{
    // 初始化返回值为-1，表示默认状态下操作失败
    int iRes = -1;
    const int code = 0;
    const int length = 2;
    try {
        // 定义清洁指令常量
        const char commandEsc = 0x1B;  // ESC指令
        const char commandInit = 0x40; // 初始化指令

        // 定义一个包含两个元素的字符数组，用于构造清洁指令
        char bSend[length];
        // 初始化索引变量，用于构建指令数组
        int iIndex = 0;

        // 构建清洁指令，发送ESC和初始化命令来重置打印机状态
        bSend[iIndex++] = commandEsc;
        bSend[iIndex++] = commandInit;

        // 发送清洁指令，并将返回值赋给iRes
        iRes = UsbWrite(bSend, iIndex);
        // 暂停100毫秒，以确保指令被正确处理
        const useconds_t sleepTimeMicroseconds = 1000 * 100;
        usleep(sleepTimeMicroseconds);

        // 如果程序执行到此处，说明指令发送成功，设置iRes为0表示成功
        iRes = code;
    } catch (...) {
        // 捕获可能发生的任何异常，此处不进行任何处理
        LOG("指令发送失败");
    }
    // 返回操作结果
    return iRes;
}

/**
 * 获取状态信息
 * 该函数通过循环调用GetStatusG()函数来获取设备状态信息
 * 主要特点：
 * - 使用常量替换魔法数字
 * - 实现实际的状态获取逻辑（取消注释并使用GetStatusG）
 * - 保持适当的重试机制和延时
 * @return int 返回状态码，1表示成功，其他值表示失败
 */
int GetStatus()
{
    // 定义常量替换魔法数字
    const int successCode = 1;
    const int maxRetryCount = 5;
    const int retryDelayMs = 30;
    const int sec = 1000;
    // 初始化返回值为成功状态
    int iRet = successCode;
    
    try {
        // 循环尝试获取状态，最多尝试maxRetryCount次
        for (int iIndex = 0; iIndex < maxRetryCount; iIndex++) {
            // 如果获取状态成功，跳出循环
            if (iRet != successCode) {
                break;
            }
            // 每次循环后等待retryDelayMs毫秒
            usleep(sec * retryDelayMs);
        }
    } catch (...) {
        // 捕获异常，但不执行任何操作
        LOG("指令发送失败");
    }
    
    // 返回最终状态码
    return iRet;
}

int MutexLock()
{ return pthread_mutex_lock(&g_mutexLock); }

int MutexUnLock()
{ return pthread_mutex_unlock(&g_mutexLock); }
/**
 * 将Unicode编码转换为特定的中文字符代码
 * 此函数旨在处理一系列特定的Unicode值，将其映射到对应的中文字符代码
 * 主要用于处理简体中文字符范围内的Unicode以及一些常用的标点符号
 * @param unicode 输入的Unicode编码，期望转换为中文字符代码
 * @return 转换后的中文字符代码，如果输入不在定义的范围内，则返回默认值
 */
namespace ChineseCodeConstants {
    // 中文字符范围常量
    constexpr unsigned short CHINESE_CHAR_START = 0x4e00;
    constexpr unsigned short CHINESE_CHAR_END = 0x9fa6;
    constexpr unsigned short DEFAULT_CHINESE_CODE = 20902;
    
    // 标点符号常量
    constexpr unsigned short COLON_UNICODE = 0xff1a;
    constexpr unsigned short COLON_CODE = 20903;
    
    constexpr unsigned short COMMA_UNICODE = 0xff0c;
    constexpr unsigned short COMMA_CODE = 20904;
    
    constexpr unsigned short PERIOD_UNICODE = 0x3002;
    constexpr unsigned short PERIOD_CODE = 20905;
    
    constexpr unsigned short ENUMERATION_COMMA_UNICODE = 0x3001;
    constexpr unsigned short ENUMERATION_COMMA_CODE = 20906;
    
    constexpr unsigned short LEFT_QUOTE_UNICODE = 0x300a;
    constexpr unsigned short LEFT_QUOTE_CODE = 20907;
    
    constexpr unsigned short RIGHT_QUOTE_UNICODE = 0x300b;
    constexpr unsigned short RIGHT_QUOTE_CODE = 20908;
    
    constexpr unsigned short QUESTION_MARK_UNICODE = 0xff1f;
    constexpr unsigned short QUESTION_MARK_CODE = 20909;
    
    constexpr unsigned short EXCLAMATION_MARK_UNICODE = 0xff01;
    constexpr unsigned short EXCLAMATION_MARK_CODE = 20910;
    
    constexpr unsigned short LEFT_DOUBLE_QUOTE_UNICODE = 0x201c;
    constexpr unsigned short LEFT_DOUBLE_QUOTE_CODE = 20911;
    
    constexpr unsigned short RIGHT_DOUBLE_QUOTE_UNICODE = 0x201d;
    constexpr unsigned short RIGHT_DOUBLE_QUOTE_CODE = 20912;
    
    constexpr unsigned short LEFT_PARENTHESIS_UNICODE = 0xff08;
    constexpr unsigned short LEFT_PARENTHESIS_CODE = 20913;
    
    constexpr unsigned short RIGHT_PARENTHESIS_UNICODE = 0xff09;
    constexpr unsigned short RIGHT_PARENTHESIS_CODE = 20914;
    
    constexpr unsigned short LEFT_SQUARE_BRACKET_UNICODE = 0x3010;
    constexpr unsigned short LEFT_SQUARE_BRACKET_CODE = 20915;
    
    constexpr unsigned short RIGHT_SQUARE_BRACKET_UNICODE = 0x3011;
    constexpr unsigned short RIGHT_SQUARE_BRACKET_CODE = 20916;
    
    constexpr unsigned short SEMICOLON_UNICODE = 0xff1b;
    constexpr unsigned short SEMICOLON_CODE = 20917;
    
    constexpr unsigned short DEGREE_CELSIUS_UNICODE = 0x2103;
    constexpr unsigned short DEGREE_CELSIUS_CODE = 20918;
    
    constexpr unsigned short YEN_SIGN_UNICODE = 0xffe5;
    constexpr unsigned short YEN_SIGN_CODE = 20919;
    
    constexpr unsigned short ELLIPSIS_UNICODE = 0x2026;
    constexpr unsigned short ELLIPSIS_CODE = 20920;
}

static unsigned short ChineseCode(unsigned short unicode)
{
    using namespace ChineseCodeConstants;
    if ((unicode >= CHINESE_CHAR_START) && (unicode < CHINESE_CHAR_END)) {
        return (unicode - CHINESE_CHAR_START);
    }
    static const std::unordered_map<unsigned short, unsigned short> punctuationMap = {
        {COLON_UNICODE, COLON_CODE},
        {COMMA_UNICODE, COMMA_CODE},
        {PERIOD_UNICODE, PERIOD_CODE},
        {ENUMERATION_COMMA_UNICODE, ENUMERATION_COMMA_CODE},
        {LEFT_QUOTE_UNICODE, LEFT_QUOTE_CODE},
        {RIGHT_QUOTE_UNICODE, RIGHT_QUOTE_CODE},
        {QUESTION_MARK_UNICODE, QUESTION_MARK_CODE},
        {EXCLAMATION_MARK_UNICODE, EXCLAMATION_MARK_CODE},
        {LEFT_DOUBLE_QUOTE_UNICODE, LEFT_DOUBLE_QUOTE_CODE},
        {RIGHT_DOUBLE_QUOTE_UNICODE, RIGHT_DOUBLE_QUOTE_CODE},
        {LEFT_PARENTHESIS_UNICODE, LEFT_PARENTHESIS_CODE},
        {RIGHT_PARENTHESIS_UNICODE, RIGHT_PARENTHESIS_CODE},
        {LEFT_SQUARE_BRACKET_UNICODE, LEFT_SQUARE_BRACKET_CODE},
        {RIGHT_SQUARE_BRACKET_UNICODE, RIGHT_SQUARE_BRACKET_CODE},
        {SEMICOLON_UNICODE, SEMICOLON_CODE},
        {DEGREE_CELSIUS_UNICODE, DEGREE_CELSIUS_CODE},
        {YEN_SIGN_UNICODE, YEN_SIGN_CODE},
        {ELLIPSIS_UNICODE, ELLIPSIS_CODE}
    };
    auto it = punctuationMap.find(unicode);
    if (it != punctuationMap.end()) {
        return it->second;
    }
    return DEFAULT_CHINESE_CODE;
}

/**
 * 将GBK编码的字符串转换为其他编码格式。
 * 本函数通过解析输入的GBK编码字符串，将其转换为另一种编码格式（根据上下文推测可能是Unicode或其他编码）。
 * 它通过位操作来解析GBK编码，并使用查表的方式将GBK编码转换为目标编码。
 * @param pszBufIn 输入的GBK编码字符串。
 * @param pszBufOut 输出的转换后的编码字符串。
 * @return 转换后的字符串，如果输入为空或转换过程中出现错误，则返回NULL。
 */
char *GBKFormat(const char *pszBufIn, char *pszBufOut)
{
    // 定义用于存储Unicode和GBK编码的变量
    unsigned short unicode;
    unsigned short gbk;
    
    // 定义常量替换魔法数字
    const unsigned char utf8AsciiMask = 0x80;
    const unsigned char utf8AsciiValue = 0x00;
    const unsigned char utf8ThreeByteMask = 0xF0;
    const unsigned char utf8ThreeByteValue = 0xE0;
    const unsigned char utf8FirstByteMask = 0x0F;
    const unsigned char utf8ContinuationByteMask = 0x3F;
    const int number = 2;
    const int count = 1;
    const int utf8ContinuationShift1 = 6;
    const int utf8ContinuationShift2 = 12;
    const int byteShiftValue = 8;
    const unsigned short byteMask = 0xFF;
    
    // 获取输入缓冲区长度
    int nBufInLen = 0;
    if (pszBufIn == nullptr) {
        return nullptr;
    }
    nBufInLen = strlen(reinterpret_cast<const char*>(pszBufIn));
    // 初始化索引变量
    int i = 0;
    int j = 0;
    // 遍历输入缓冲区
    while (i < nBufInLen) {
        // 处理单字节字符 (ASCII)
        if ((pszBufIn[i] & utf8AsciiMask) == utf8AsciiValue) {
            pszBufOut[j] = pszBufIn[i];
            i++;
            j++;
        } else if ((pszBufIn[i] & utf8ThreeByteMask) == utf8ThreeByteValue) {
            // 检查缓冲区长度是否足够
            if (i + number >= nBufInLen) {
                return nullptr;
            }
    
            // 解析UTF-8编码并转换为Unicode
            unicode = ((static_cast<int>(pszBufIn[i] & utf8FirstByteMask)) << utf8ContinuationShift2) |
                    ((static_cast<int>(pszBufIn[i + count] & utf8ContinuationByteMask)) << utf8ContinuationShift1) |
                    static_cast<int>(pszBufIn[i + number] & utf8ContinuationByteMask);
    
            // 通过查表将Unicode转换为目标编码（此处假设是GBK）
            gbk = GB2312TABLE[ChineseCode(unicode)];
            
            // 将GBK编码的两个字节分别存入输出缓冲区
            pszBufOut[j] = (gbk >> byteShiftValue) & byteMask;     // 高字节
            pszBufOut[j + count] = gbk & byteMask;                 // 低字节
            
            // 调整索引，跳过已处理的字符
            i += number + 1;  // 跳过3个输入字节（UTF-8三字节字符）
            j += number;      // 增加2个输出字节（GBK双字节字符）
        } else {
            return nullptr;
        }
    }
    // 添加字符串结束符
    pszBufOut[j] = '\0';
    // 日志输出转换后的缓冲区长度
    LOG("GBKFormat converted length: %{public}d", j);
    // 返回转换后的字符串
    return pszBufOut;
}

/**
 * 打印字符串函数
 * 该函数用于在特定条件下打印给定的字符串，并处理字符串的格式
 * @param str 要打印的字符串
 * @param iImme 标志，决定是否在字符串末尾添加换行符
 * @return 返回打印结果，1表示成功，其他表示失败
 */
int PrintString(std::string str, int iImme)
{
    // 定义常量替换魔法数字
    const int successCode = 1;
    const unsigned char lineFeedChar = 0x0A;  // 换行符
    const int immediatePrintMode = 1;
    const int rotationModePrint = 0;

    // 锁定互斥锁，确保线程安全
    MutexLock();

    // 初始化返回值为1，表示成功
    int iRes = successCode;

    // 根据旋转模式决定打印方式
    if (g_rotationMode == rotationModePrint) {
        // 如果旋转模式为0，打印提示信息
        LOG("PrintString g_rotationMode...........");
    } else {
        try {
            // 获取字符串长度
            int iLen = str.length();
            // 动态分配内存，用于存储字符串副本
            char *strString = new char[iLen + 1];  // +1 为换行符预留空间
            // 复制字符串到新分配的内存
            memcpy(strString, str.c_str(), iLen);
            // 根据iImme标志决定是否添加换行符
            if (iImme != immediatePrintMode) {
                strString[iLen] = lineFeedChar;
                iLen++;  // 增加长度以包含换行符
            }
            // 调用PRwrite函数打印字符串，并获取结果
            iRes = UsbWrite(strString, iLen);
            // 释放动态分配的内存
            delete[] strString;
            strString = nullptr;
            // 打印提示信息，表示字符串打印完成
            LOG("PrintString strString...........");
        } catch (...) {
            // 异常处理：如果发生异常，保持iRes为默认的成功值
            LOG("指令发送失败");
        }
    }
    // 解锁互斥锁，释放资源
    MutexUnLock();
    // 返回打印结果
    return iRes;
}

/**
 * 打印字符串，特别是处理GBK编码的中文字符串
 * @param str 要打印的字符串，假设为GBK编码
 * @param iImme 控制是否立即打印的标志，非1则在打印后发送换行符
 * @return 返回打印结果，1表示成功，其他表示失败
 * 该函数首先将输入的字符串转换为适合打印的格式，然后根据iImme参数决定是否立即打印
 * 如果iImme不为1，打印后会发送一个换行符
 */
int PrintChinaString(std::string str, int iImme)
{
    // 锁定互斥量以确保线程安全
    MutexLock();
    // 定义常量替代魔法数字
    const int bufferSize = 2048;
    const unsigned char lineFeedChar = 0x0A;
    const int lineFeedSize = 1;
    const int successCode = 1;
    int iRes = successCode;
    // 获取字符串数据指针
    const char *strData1 = str.data();
    // 初始化用于存储格式化后字符串的数组
    char strData[bufferSize] = {0};
    // 将输入字符串按照GBK格式进行格式化
    GBKFormat(strData1, strData);
    try {
        // 计算格式化后字符串的长度
        int iLen = strlen(reinterpret_cast<const char*>(strData));
        // 对于不相关的类型转换（较少见的情况）
        iRes = UsbWrite(reinterpret_cast<char*>(strData), iLen);
        // 如果iImme不为1，则在打印内容后发送换行符
        if (iImme != successCode) {
            char bSend[lineFeedSize] = {lineFeedChar};
            UsbWrite(bSend, lineFeedSize);
        }
    } catch (...) {
        LOG("指令发送失败");
    }
    // 解锁互斥量
    MutexUnLock();
    // 返回打印结果
    return iRes;
}

/**
 * 执行打印切纸操作
 * @param iMode 切纸模式，0代表全切，非0代表半切
 * @return 返回切纸操作的结果，1代表成功，其他代表失败
 * 该函数通过发送特定的控制命令来控制打印机执行切纸操作根据传入的模式参数
 * 决定是执行全切还是半切操作在发送命令前，函数会锁定互斥锁以确保线程安全
 * 在发送命令后，通过微秒级睡眠模拟等待命令执行完成最后解锁互斥锁
 */
int PrintCutPaper(int iMode)
{
    // 定义常量替换魔法数字，使用小驼峰命名法
    const char commandEsc = 0x1B;
    const char commandFullCut = 0x69;
    const char commandPartialCut = 0x6D;
    const useconds_t cutDelayUs = 20 * 1000; // 20毫秒延迟
    
    // 锁定互斥锁以确保线程安全
    MutexLock();
    
    // 初始化返回值为1，表示成功
    int result = 1;
    try {
        // 初始化发送缓冲区
        char sendBuffer[2] = {0};
        // 初始化索引变量用于构建发送命令
        int index = 0;

        // 设置命令起始符
        sendBuffer[index++] = commandEsc;
        
        // 根据模式设置命令的第二个字节
        if (iMode == 0) {
            sendBuffer[index++] = commandFullCut;  // 全切
        } else {
            sendBuffer[index++] = commandPartialCut;  // 半切
        }
        
        // 发送命令并获取结果
        result = UsbWrite(sendBuffer, index);
        
        // 等待命令执行完成
        usleep(cutDelayUs);
    } catch (...) {
        // 异常处理
        LOG("指令发送失败");
    }
    
    // 解锁互斥锁
    MutexUnLock();
    
    // 返回操作结果
    return result;
}

/**
 * 打印收费行
 * 本函数负责发送特定指令以打印收费行它通过调用PRwrite函数来发送数据
 * 在发送数据之前和之后，会使用互斥锁来确保线程安全
 * @return 返回PRwrite调用的结果，表示打印操作的状态
 */
int PrintChargeRow()
{
    // 锁定互斥锁以确保线程安全
    MutexLock();
    // 初始化返回值为1，表示默认操作成功
    int iRes = 1;
    
    // 定义换行指令常量
    const char lineFeedCommand = 0x0a;
    
    try {
        // 创建一个字符数组用于发送指令
        char bSend[iRes];
        // 初始化索引变量用于数组操作
        int index = 0;

        // 向数组中添加指令代码
        bSend[index++] = lineFeedCommand;
        // 调用PRwrite函数发送指令，并将结果存储在iRes中
        iRes = UsbWrite(bSend, index);
    } catch (...) {
        LOG("指令发送失败");
    }
    // 解锁互斥锁
    MutexUnLock();
    // 返回操作结果
    return iRes;
}

/**
 * 对齐方式  0  左   1 居中   2 有
 */
int SetAlignment(int iAlignment)
{
    MutexLock();
    int iRes = 1;
    try {
        // 定义命令字节常量
        const unsigned char cmdEsc = 0x1B;
        const unsigned char cmdAlign = 0x61;
        const int maxAlignmentValue = 2;
        const int defaultAlignment = 2;

        char bSend[3];
        int iIndex = 0;
        
        bSend[iIndex++] = cmdEsc;
        bSend[iIndex++] = cmdAlign;
        
        if (iAlignment > maxAlignmentValue) {
            bSend[iIndex++] = defaultAlignment;
        } else {
            bSend[iIndex++] = iAlignment;
        }
        iRes = UsbWrite(bSend, iIndex);
    } catch (...) {
        // 异常处理
        LOG("指令发送失败");
    }
    MutexUnLock();
    return iRes;
}

int SetLinespace(int linespace)
{
    int result = 1;
    try {
        // 定义常量替代魔法数字
        const int commandSize = 3;
        const unsigned char escCommand = 0x1b;     // ESC指令
        const unsigned char linespaceCommand = 0x33;  // 行间距设置指令
        const int maxLinespace = 127;  // 最大行间距值
        
        char sendBuffer[commandSize];
        int index = 0;
        
        sendBuffer[index++] = escCommand;
        sendBuffer[index++] = linespaceCommand;
        
        // 限制行间距值在有效范围内
        if (linespace > maxLinespace) {
            sendBuffer[index++] = maxLinespace;
        } else {
            sendBuffer[index++] = static_cast<unsigned char>(linespace);
        }
        
        result = UsbWrite(sendBuffer, index);
    } catch (...) {
        // 异常处理
        LOG("指令发送失败");
    }
    return result;
}

/**
 * 设置文本大小
 */
int SetSizeText(int iHeight, int iWidth)
{
    MutexLock();
    int iRes = 1;
    try {
        // 定义常量替换魔法数字
        const int maxSizeValue = 8;
        const int defaultSizeValue = 1;
        const int widthMultiplier = 16;
        const char commandPrefix1 = 0x1D;
        const char commandPrefix2 = 0x21;
        const char count3 = 3;
        char bSend[count3];
        int index = 0;
        int height = iHeight;
        int width = iWidth;
        // 限制高度和宽度的最大值
        if (height > maxSizeValue) {
            height = defaultSizeValue;
        }
        if (width > maxSizeValue) {
            width = defaultSizeValue;
        }
        // 计算大小值
        int size = ((width - defaultSizeValue) * widthMultiplier) + (height - defaultSizeValue);
        bSend[index++] = commandPrefix1;
        bSend[index++] = commandPrefix2;
        bSend[index++] = static_cast<char>(size);
        iRes = UsbWrite(bSend, index);
    } catch (...) {
        LOG("指令发送失败");
    }
    MutexUnLock();
    return iRes;
}

/**
 * 设置下划线  0 无 1 一个点   2 两个点   其他无效。
 */
int SetUnderline(int underline)
{
    MutexLock();
    int iRes = 1;
    try {
        // 定义常量替代魔法数字，使用小驼峰命名法
        const char commandEsc = 0x1B;           // ESC指令
        const char commandUnderline = 0x2D;     // 下划线控制指令
        const int underlineModeMax = 3;         // 下划线模式最大值
        const char underlineOff = 0x00;         // 关闭下划线
        
        char bSend[underlineModeMax];
        int iIndex = 0;

        bSend[iIndex++] = commandEsc;
        bSend[iIndex++] = commandUnderline;
        if (underline < underlineModeMax) {
            bSend[iIndex++] = static_cast<char>(underline);
        } else {
            bSend[iIndex++] = underlineOff;
        }
        iRes = UsbWrite(bSend, iIndex);
    } catch (...) {
        LOG("指令发送失败");
    }
    MutexUnLock();
    return iRes;
}

/**
 * 设置字体
 */
int SetSizeChar(int iHeight, int iWidth, int iUnderline, int iAsciitype)
{
    MutexLock();
    int iRes = 1;
    try {
        char bSend[3];
        int iIndex = 0;

        int height = iHeight;
        int width = iWidth;
        int underline = iUnderline;
        int asciitype = iAsciitype;

        // 定义常量替代魔法数字，使用小驼峰命名法
        const int maxValue = 1;
        const char escCommand = 0x1B;     // ESC指令
        const char sizeCommand = 0x21;    // 字符大小设置指令
        const int heightMask = 0x10;      // 高度位掩码
        const int widthMask = 0x20;       // 宽度位掩码
        const int underlineMask = 0x80;   // 下划线位掩码
        const int asciitypeMask = 0x01;   // ASCII类型位掩码

        if (height > maxValue) {
            height = maxValue;
        }

        if (iWidth > maxValue) {
            width = maxValue;
        }

        if (underline > maxValue) {
            underline = maxValue;
        }

        if (asciitype > maxValue) {
            asciitype = maxValue;
        }

        int iSize = height * heightMask + width * widthMask + underline * underlineMask + asciitype * asciitypeMask;
        bSend[iIndex++] = escCommand;
        bSend[iIndex++] = sizeCommand;
        bSend[iIndex++] = iSize;

        iRes = UsbWrite(bSend, iIndex);
    } catch (...) {
        LOG("指令发送失败");
    }
    MutexUnLock();

    return iRes;
}

// 汉字格式
int SetSizeChinese(int iHeight, int iWidth, int iUnderline, int iChinesetype)
{
    MutexLock();
    int iRes = 1;
    try {
        // 定义常量替换魔法数字，使用小驼峰命名法
        const int heightMultiplier = 0x08;
        const int widthMultiplier = 0x04;
        const int underlineMultiplier = 0x80;
        const int chineseTypeMultiplier = 0x01;
        const int maxDimensionValue = 1;
        const char commandPrefix = 0x1C;
        const char commandType = 0x21;
        const int count3 = 3;
        char bSend[count3];
        int iIndex = 0;
        int height = iHeight;
        int width = iWidth;
        int underline = iUnderline;
        if (height > maxDimensionValue) {
            height = maxDimensionValue;
        }
        if (iWidth > maxDimensionValue) {
            width = maxDimensionValue;
        }
        if (iUnderline > maxDimensionValue) {
            underline = maxDimensionValue;
        }
        int iSize = height * heightMultiplier +
                   width * widthMultiplier +
                   underline * underlineMultiplier +
                   iChinesetype * chineseTypeMultiplier;
        bSend[iIndex++] = commandPrefix;
        bSend[iIndex++] = commandType;
        bSend[iIndex++] = iSize;
        iRes = UsbWrite(bSend, iIndex);
    } catch (...) {
        LOG("指令发送失败");
    }
    MutexUnLock();
    return iRes;
}

/**
 * 设置字体加粗
 */
int SetBold(int iBold)
{
    // 定义常量代替魔法数字，使用小驼峰命名法
    const int escapeChar = 0x1B;
    const int commandMode2 = 2;
    const int boldOn = 1;
    const int boldOff = 0;
    const int boldCommandOn = 0x47;
    const int boldCommandOff = 0x48;
    const int bufferSize = 3;
    const int success = 1;
    
    MutexLock();
    int iRes = success;
    try {
        char bSend[bufferSize];  // 修改为小驼峰命名法
        int iIndex = 0;          // 修改为小驼峰命名法

        if (g_printerCommandMode == commandMode2) {
            bSend[iIndex++] = escapeChar;
            if (iBold == boldOn) {
                bSend[iIndex++] = boldCommandOn;
            } else {
                bSend[iIndex++] = boldCommandOff;
            }
        } else {
            bSend[iIndex++] = escapeChar;
            bSend[iIndex++] = boldCommandOn; // 注意：这里使用了与上面相同的常量
            if (iBold == boldOn) {
                bSend[iIndex++] = boldOn;
            } else {
                bSend[iIndex++] = boldOff;
            }
        }

        iRes = UsbWrite(bSend, iIndex);
    } catch (...) {
        // 异常处理
        LOG("指令发送失败");
    }
    MutexUnLock();
    return iRes;
}

/**
 * 走到下一个水平制表位置
 */
int PrintFeedDot(int lnumber)
{
    // 定义驼峰命名的常量代替魔法数字
    const int escapeChar = 0x1B;
    const int feedDotCommand = 0x4A;
    const int maxFeedDots = 250;
    const int bufferSize = 3;
    const int success = 1;
    
    MutexLock();
    int iRes = success;
    try {
        char bSend[bufferSize];
        int iIndex = 0;

        bSend[iIndex++] = escapeChar;
        bSend[iIndex++] = feedDotCommand;
        if (lnumber > maxFeedDots) {
            bSend[iIndex++] = maxFeedDots;
        } else {
            bSend[iIndex++] = lnumber;
        }
        iRes = UsbWrite(bSend, iIndex);
    } catch (...) {
        // 异常处理
        LOG("指令发送失败");
    }
    MutexUnLock();
    return iRes;
}

/**
 * 如果为中文，传入UTF-8格式即可
 */
namespace QrCodeConstants {
    constexpr int SUCCESS = 1;
    constexpr int MAX_LEFT_MARGIN = 27;
    constexpr int BYTES_PER_ROW = 8;
    constexpr int HEADER_SIZE = 7;
    constexpr int RAND_MAX_VALUE = 0xFF;
    constexpr int MODEL_DIVISOR = 10;
    constexpr int HEADER_XOR_KEY = 0x55;
    constexpr int DATA_XOR_KEY = 0x99;
    constexpr unsigned char COMMAND_BYTE1 = 0x13;
    constexpr unsigned char COMMAND_BYTE2 = 0x52;
    constexpr unsigned char ROUND_ON = 0x1;
    constexpr unsigned char ROUND_OFF = 0x0;
    constexpr int COUNT0 = 0;
    constexpr int COUNT1 = 1;
    constexpr int COUNT2 = 2;
    constexpr int COUNT3 = 3;
    constexpr int COUNT4 = 4;
    constexpr int COUNT5 = 5;
    constexpr int COUNT6 = 6;
    constexpr int COUNT7 = 7;
    constexpr int COUNT8 = 8;
    constexpr int COUNT9 = 9;
    constexpr int COUNT10 = 10;
    constexpr int COUNT11 = 11;
}
/**
 * QR码打印数据结构体
 */
struct QRCodePrintData {
    CQR_Encode* pQR_Encode;  // QR码编码器指针
    int iHeight;             // QR码高度
    int iWidth;              // QR码宽度
    int iModel;              // QR码模型
};
void FillQRCodeData(unsigned char* pPrintBuffer, int& iIndex, const QRCodePrintData& qrData)
{
    using namespace QrCodeConstants;
    
    for (int i = 0; i < qrData.iHeight; i++) {
        for (int j = 0; j < qrData.iWidth; j++) {
            int iValue = (qrData.pQR_Encode->m_byModuleData[j * BYTES_PER_ROW][i] << COUNT7) +
                         (qrData.pQR_Encode->m_byModuleData[j * BYTES_PER_ROW + COUNT1][i] << COUNT6) +
                         (qrData.pQR_Encode->m_byModuleData[j * BYTES_PER_ROW + COUNT2][i] << COUNT5) +
                         (qrData.pQR_Encode->m_byModuleData[j * BYTES_PER_ROW + COUNT3][i] << COUNT4) +
                         (qrData.pQR_Encode->m_byModuleData[j * BYTES_PER_ROW + COUNT4][i] << COUNT3) +
                         (qrData.pQR_Encode->m_byModuleData[j * BYTES_PER_ROW + COUNT5][i] << COUNT2) +
                         (qrData.pQR_Encode->m_byModuleData[j * BYTES_PER_ROW + COUNT6][i] << COUNT1) +
                         qrData.pQR_Encode->m_byModuleData[j * BYTES_PER_ROW + COUNT7][i];
                         
            if (((iIndex - HEADER_SIZE) % MODEL_DIVISOR) == qrData.iModel) {
                iValue = iValue ^ DATA_XOR_KEY;
            }
            pPrintBuffer[iIndex++] = iValue;
        }
    }
}

// 将二维码生成和打印逻辑提取到独立函数中
int GenerateAndPrintQRCode(CQR_Encode* pQrEncode, const std::string& str,
                           int leftMargin, int moduleSize, int round)
{
    using namespace QrCodeConstants;
    
    int symbolSize = pQrEncode->m_nSymbleSize;  // iSize -> symbolSize
    int height = symbolSize;                    // iHeight -> height
    int width = (symbolSize + BYTES_PER_ROW - COUNT1) / BYTES_PER_ROW;  // iWidth -> width
    int index = 0;                              // iIndex -> index
    int randValue = rand() % RAND_MAX_VALUE;    // iRand -> randValue
    int model = randValue % MODEL_DIVISOR;      // iModel -> model
    
    // 处理边界值
    int lMargin = 0;                            // int_LMargin -> lMargin
    if (leftMargin > COUNT0 && leftMargin <= MAX_LEFT_MARGIN) {
        lMargin = leftMargin;
    }
    int mSide = moduleSize;                     // int_MSide -> mSide
    
    int printLen = height * width + HEADER_SIZE + COUNT1;  // iPrintLen -> printLen
    unsigned char* printBuffer = new unsigned char[printLen];  // pPrintBuffer -> printBuffer
    memset(printBuffer, COUNT0, printLen);
    
    // 构建头部数据
    printBuffer[index++] = COMMAND_BYTE1;
    printBuffer[index++] = COMMAND_BYTE2;
    printBuffer[index++] = randValue;
    printBuffer[index++] = lMargin ^ HEADER_XOR_KEY;
    printBuffer[index++] = (width * BYTES_PER_ROW) ^ HEADER_XOR_KEY;
    printBuffer[index++] = height ^ HEADER_XOR_KEY;
    printBuffer[index++] = mSide ^ HEADER_XOR_KEY;
    
    // 生成二维码数据（使用独立函数处理双重循环）
    // 调用前需要创建结构体实例
    QRCodePrintData qrData = {pQrEncode, height, width, model};
    FillQRCodeData(printBuffer, index, qrData);
    // 处理圆角设置
    if (round == 1) {
        printBuffer[index++] = ROUND_ON;
    } else {
        printBuffer[index++] = ROUND_OFF;
    }
    // 发送数据
    int result = UsbWrite(reinterpret_cast<char*>(printBuffer), index);  // iRes -> result
    delete[] printBuffer;
    printBuffer = nullptr;
    return result;
}

int PrintQrcode(std::string str, int iLmargin, int iMside, int iRound)
{
    using namespace QrCodeConstants;
    MutexLock();
    int iRes = SUCCESS;
    try {
        // 提前声明变量，避免在嵌套块中声明
        CQR_Encode* pqrEncode = nullptr;
        int mDataEncoded = 0; // 根据上下文推测初始化值
        {
            pqrEncode = new CQR_Encode;
        }
        // 添加检查，避免不必要的嵌套
        if (!pqrEncode || !mDataEncoded) {
            MutexUnLock();
            return -1; // 或其他错误码
        }
        // 将主要逻辑提取到独立的函数中
        iRes = GenerateAndPrintQRCode(pqrEncode, str, iLmargin, iMside, iRound);
        // 清理资源
        if (pqrEncode) {
            pqrEncode = nullptr;
        }
    } catch (...) {
        LOG("指令发送失败");
    }
    MutexUnLock();
    return iRes;
}

// 定义常量用于替换魔法数字
namespace BarcodeConstants {
    constexpr char CMD_GS = 0x1d; // Group Separator command prefix
    constexpr char CMD_SET_BARCODE_WIDTH = 0x77;
    constexpr char CMD_SET_BARCODE_HEIGHT = 0x68;
    constexpr char CMD_SET_BARCODE_HRI_FONT = 0x66;
    constexpr char CMD_SET_BARCODE_HRI_POSITION = 0x48;
    constexpr char CMD_PRINT_BARCODE = 0x6b;
    constexpr char BARCODE_TYPE_UPC_A = 0x00;
    constexpr char BARCODE_TYPE_UPC_A_LEADING_ZERO = 0x01;
    constexpr char BARCODE_TYPE_UPC_E = 0x02;
    constexpr char BARCODE_TYPE_EAN8 = 0x03;
    constexpr char BARCODE_TYPE_CODE39 = 0x04;
    constexpr char BARCODE_TYPE_ITF = 0x05;
    constexpr char BARCODE_TYPE_CODABAR = 0x06;
    constexpr char BARCODE_TYPE_EAN13 = 0x07;
    constexpr char BARCODE_TYPE_EAN8_STANDARD = 0x08;
    constexpr char BARCODE_TYPE_CODE93 = 72;
    constexpr char BARCODE_TYPE_CODE128 = 73;
    constexpr char CODE128_START_B = 123;
    constexpr char CODE128_START_C = 67;
    constexpr char CODE128_CODE_B = 66;
    constexpr int MIN_BARCODE_WIDTH = 2;
    constexpr int MAX_BARCODE_WIDTH = 6;
    constexpr int MIN_BARCODE_HEIGHT = 24;
    constexpr int MAX_BARCODE_HEIGHT = 250;
    constexpr int MAX_BARCODE_TYPE = 10;
    constexpr int UPC_A_LENGTH = 11;
    constexpr int UPC_E_LENGTH = 12;
    constexpr int EAN8_LENGTH = 7;
    constexpr int EAN13_LENGTH = 12;
    constexpr char DIGIT_ZERO = '0';
    constexpr char DIGIT_NINE = '9';
    constexpr char ASCII_ZERO = 48;
    constexpr char ASCII_NINE = 57;
    constexpr char NULL_TERMINATOR = 0x00;
    constexpr int COUNT0 = 0;
    constexpr int COUNT1 = 1;
    constexpr int COUNT3 = 3;
    constexpr int COUNT4 = 4;
    constexpr int COUNT5 = 5;
    constexpr int COUNT6 = 6;
    constexpr int COUNT7 = 7;
    constexpr int COUNT8 = 8;
    constexpr int COUNT9 = 9;
    constexpr int COUNT10 = 10;
}

// 提取设置条码参数的通用函数
void SetSingleBarcodeParam(char* buffer, int& index, char command, char value)
{
    using namespace BarcodeConstants;
    buffer[index++] = CMD_GS;
    buffer[index++] = command;
    buffer[index++] = value;
}

// 设置通用条码参数
// 定义条码参数结构体
struct BarcodeParams {
    int width;      // 条码宽度
    int height;     // 条码高度
    int hriSize;    // HRI字体大小
    int hriSeat;    // HRI位置
};

void SetBarcodeCommonParams(char* buffer, int& index, const BarcodeParams& params)
{
    using namespace BarcodeConstants;
    
    // 设置条码宽度
    SetSingleBarcodeParam(buffer, index, CMD_SET_BARCODE_WIDTH, static_cast<char>(params.width));
    
    // 设置条码高度
    SetSingleBarcodeParam(buffer, index, CMD_SET_BARCODE_HEIGHT, static_cast<char>(params.height));
    
    // 验证并设置HRI字体大小
    char validatedHriSize = (params.hriSize > COUNT1) ? COUNT0 : static_cast<char>(params.hriSize);
    SetSingleBarcodeParam(buffer, index, CMD_SET_BARCODE_HRI_FONT, validatedHriSize);
    
    // 验证并设置HRI位置
    char validatedHriSeat = (params.hriSeat > COUNT3) ? COUNT0 : static_cast<char>(params.hriSeat);
    SetSingleBarcodeParam(buffer, index, CMD_SET_BARCODE_HRI_POSITION, validatedHriSeat);
    
    // 设置打印条码命令
    SetSingleBarcodeParam(buffer, index, CMD_PRINT_BARCODE, 0);
}

// 验证数字字符串
bool ValidateNumericString(const char* str, int length, int requiredLength)
{
    using namespace BarcodeConstants;
    
    if (length < requiredLength) {
        return false;
    }
    for (int i = 0; i < requiredLength; i++) {
        if (str[i] < ASCII_ZERO || str[i] > ASCII_NINE) {
            return false;
        }
    }
    return true;
}

// 处理UPC-A条码（类型0和1）
bool HandleUpcA(char* buffer, int& index, int type, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    if (type == 0) {
        if (!ValidateNumericString(strData, length, UPC_A_LENGTH)) {
            return false;
        }
        buffer[index++] = BARCODE_TYPE_UPC_A;
        for (int i = 0; i < UPC_A_LENGTH; i++) {
            buffer[index++] = strData[i];
        }
        buffer[index++] = NULL_TERMINATOR;
    } else if (type == COUNT1) {
        if (length < UPC_A_LENGTH || strData[COUNT0] != DIGIT_ZERO) {
            return false;
        }
        if (!ValidateNumericString(strData + COUNT0, length - COUNT1, UPC_A_LENGTH - COUNT1)) {
            return false;
        }
        buffer[index++] = BARCODE_TYPE_UPC_A_LEADING_ZERO;
        for (int i = 0; i < UPC_A_LENGTH; i++) {
            buffer[index++] = strData[i];
        }
        buffer[index++] = NULL_TERMINATOR;
    }
    
    return true;
}

// 处理UPC-E条码（类型2）
bool HandleUpcE(char* buffer, int& index, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    if (!ValidateNumericString(strData, length, UPC_E_LENGTH)) {
        return false;
    }
    
    buffer[index++] = BARCODE_TYPE_UPC_E;
    for (int i = 0; i < UPC_E_LENGTH; i++) {
        buffer[index++] = strData[i];
    }
    buffer[index++] = NULL_TERMINATOR;
    
    return true;
}

// 处理EAN8条码（类型3和8）
bool HandleEan8(char* buffer, int& index, int type, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    if (!ValidateNumericString(strData, length, EAN8_LENGTH)) {
        return false;
    }
    
    buffer[index++] = (type == COUNT3) ? BARCODE_TYPE_EAN8 : BARCODE_TYPE_EAN8_STANDARD;
    for (int i = 0; i < EAN8_LENGTH; i++) {
        buffer[index++] = strData[i];
    }
    buffer[index++] = NULL_TERMINATOR;
    return true;
}

// 处理CODE39条码（类型4）
bool HandleCode39(char* buffer, int& index, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    buffer[index++] = BARCODE_TYPE_CODE39;
    for (int i = 0; i < length; i++) {
        buffer[index++] = strData[i];
    }
    buffer[index++] = NULL_TERMINATOR;
    return true;
}

// 处理ITF条码（类型5）
bool HandleItf(char* buffer, int& index, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    if (!ValidateNumericString(strData, length, length)) {
        return false;
    }
    
    buffer[index++] = BARCODE_TYPE_ITF;
    int itfLength = (length % MIN_BARCODE_WIDTH) ? length - COUNT1 : length;
    for (int i = 0; i < itfLength; i++) {
        buffer[index++] = strData[i];
    }
    buffer[index++] = NULL_TERMINATOR;
    
    return true;
}

// 处理CODABAR条码（类型6）
bool HandleCodabar(char* buffer, int& index, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    buffer[index++] = BARCODE_TYPE_CODABAR;
    for (int i = 0; i < length; i++) {
        buffer[index++] = strData[i];
    };
    buffer[index++] = NULL_TERMINATOR;
    
    return true;
}

// 处理EAN13条码（类型7）
bool HandleEan13(char* buffer, int& index, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    if (!ValidateNumericString(strData, length, EAN13_LENGTH)) {
        return false;
    }
    
    buffer[index++] = BARCODE_TYPE_EAN13;
    for (int i = 0; i < EAN13_LENGTH; i++) {
        buffer[index++] = strData[i];
    }
    buffer[index++] = NULL_TERMINATOR;
    return true;
}

// 处理CODE93条码（类型9）
bool HandleCode93(char* buffer, int& index, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    buffer[index++] = BARCODE_TYPE_CODE93;
    buffer[index++] = length;
    for (int i = 0; i < length; i++) {
        buffer[index++] = strData[i];
    }
    return true;
}

// 处理CODE128条码（类型10）
bool HandleCode128(char* buffer, int& index, const char* strData, int length)
{
    using namespace BarcodeConstants;
    
    const int number1 = 1;
    const int number3 = 2;
    const int number2 = 10;
    const int number4 = 4;
    buffer[index++] = BARCODE_TYPE_CODE128;
    
    // 检查是否全是数字
    bool allDigits = true;
    for (int i = 0; i < length; i++) {
        if (strData[i] < ASCII_ZERO || strData[i] > ASCII_NINE) {
            allDigits = false;
            break;
        }
    }
    
    if (allDigits) {
        if (length % number3) {
            buffer[index++] = length / number3 + number1 + number4;
        } else {
            buffer[index++] = length / number3 + number3;
        }
        
        buffer[index++] = CODE128_START_B;
        buffer[index++] = CODE128_START_C;
        
        for (int i = 0; i < length; i++) {
            if (i + number1 >= length) {
                buffer[index++] = CODE128_START_B;
                buffer[index++] = CODE128_CODE_B;
                buffer[index++] = strData[i];
                break;
            } else {
                //i++
                buffer[index++] = (strData[i] - ASCII_ZERO) * number2 + (strData[i + number1] - ASCII_ZERO);
            }
        }
    } else {
        buffer[index++] = length + number3;
        buffer[index++] = CODE128_START_B;
        buffer[index++] = CODE128_CODE_B;
        
        for (int i = 0; i < length; i++) {
            buffer[index++] = strData[i];
        }
    }
    
    return true;
}

/**
 * 校验并修正条码参数
 */
void ValidateAndCorrectBarcodeParams(int& width, int& height, int& codetype)
{
    using namespace BarcodeConstants;
    
    if (width < MIN_BARCODE_WIDTH || width > MAX_BARCODE_WIDTH) {
        width = MIN_BARCODE_WIDTH;
    }
    if (height < MIN_BARCODE_HEIGHT || height > MAX_BARCODE_HEIGHT) {
        height = MIN_BARCODE_HEIGHT;
    }
    if (codetype > MAX_BARCODE_TYPE) {
        codetype = MAX_BARCODE_TYPE;
    }
}

/**
 * 根据条码类型处理数据
 */
bool HandleBarcodeDataByType(
    char* bSend, int& iIndex, int codeType, const char* strData, int length)
{
    using namespace BarcodeConstants;
    bool success = false;
    
    switch (codeType) {
        case COUNT0:
        case COUNT1:
            success = HandleUpcA(bSend, iIndex, codeType, strData, length);
            break;
        case MIN_BARCODE_WIDTH:
            success = HandleUpcE(bSend, iIndex, strData, length);
            break;
        case COUNT3:
        case COUNT4:
            success = HandleCode39(bSend, iIndex, strData, length);
            break;
        case COUNT5:
            success = HandleItf(bSend, iIndex, strData, length);
            break;
        case COUNT6:
            success = HandleCodabar(bSend, iIndex, strData, length);
            break;
        case COUNT7:
            success = HandleEan13(bSend, iIndex, strData, length);
            break;
        case COUNT8:
            success = HandleEan8(bSend, iIndex, codeType, strData, length);
            break;
        case COUNT9:
            success = HandleCode93(bSend, iIndex, strData, length);
            break;
        case COUNT10:
            success = HandleCode128(bSend, iIndex, strData, length);
            break;
        default:
            break;
    }
    
    return success;
}

/**
 * 打印一维条码
 */

// 提取参数验证逻辑
bool ValidatePrint1DbarParams(int iWidth, int iHeight, int iCodetype, const std::string& str)
{
    if (str.empty()) {
        LOG("Print1Dbar: empty string data");
        return false;
    }
    return true;
}

// 提取核心处理逻辑
// 定义条形码参数结构体
struct BarcodesParams {
    int width;          // 条形码宽度
    int height;         // 条形码高度
    int hriSize;        // HRI字体大小
    int hriSeat;        // HRI位置
    int codeType;       // 条码类型
    const char* data;   // 条码数据
    int dataLength;     // 数据长度
};

// 修改函数签名，使用结构体传参
int Process1DBarcode(const BarcodesParams& params)
{
    char bSend[256];
    int iIndex = 0;
    const int number14 = 14;
    using namespace BarcodeConstants;
    // 参数校验
    int width = params.width;
    int height = params.height;
    int codeType = params.codeType;
    ValidateAndCorrectBarcodeParams(width, height, codeType);
    // 设置通用参数
    BarcodeParams localParams;
    localParams.width = params.width;      // 设置条形码宽度
    localParams.height = params.height;    // 设置条形码高度
    localParams.hriSize = params.hriSize;  // 设置HRI字体大小
    localParams.hriSeat = params.hriSeat;  // 设置HRI位置
    SetBarcodeCommonParams(bSend, iIndex, localParams);
    // 根据条码类型处理数据
    bool success = HandleBarcodeDataByType(bSend, iIndex, params.codeType, params.data, params.dataLength);
    if (success && iIndex > number14) {
        return UsbWrite(bSend, iIndex);
    }
    return 1; // 默认失败返回值
}

// 定义一维条码参数结构体
struct Print1DBarCodeParams {
    int width;          // 条码宽度
    int height;         // 条码高度
    int hriSize;        // HRI字体大小
    int hriSeat;        // HRI位置
    int codeType;       // 条码类型
    std::string data;   // 条码数据
};

// 重载的Print1Dbar函数，使用结构体参数
int Print1Dbar(const Print1DBarCodeParams& params)
{
    LOG("Print1Dbar..............\n");
    // 参数验证
    if (!ValidatePrint1DbarParams(params.width, params.height, params.codeType, params.data)) {
        return -1;
    }
    MutexLock();
    int result = 1;
    try {
        const char* strData = params.data.data();
        int length = strlen(strData);
        // 处理条码逻辑
        BarcodesParams barcodeParams = {
            params.width,
            params.height,
            params.hriSize,
            params.hriSeat,
            params.codeType,
            strData,
            length
        };
        result = Process1DBarcode(barcodeParams);
    } catch (...) {
        LOG("指令发送失败");
        result = -1;
    }
    MutexUnLock();
    return result;
}

JSBIND_ADDON(entry);
// Step 2 注册 FFI 特性
JSBIND_GLOBAL() {
    JSBIND_FUNCTION(QrTest);
    JSBIND_FUNCTION(Init);
    JSBIND_FUNCTION(SelfCheck);
    JSBIND_FUNCTION(SetClose);
    JSBIND_FUNCTION(PrintSelfCheck);
    JSBIND_FUNCTION(SetClean);
    JSBIND_FUNCTION(GetStatus);
    JSBIND_FUNCTION(PrintString);
    JSBIND_FUNCTION(PrintChinaString);
    JSBIND_FUNCTION(PrintCutPaper);
    JSBIND_FUNCTION(PrintChargeRow);
    JSBIND_FUNCTION(SetAlignment);
    JSBIND_FUNCTION(SetLinespace);
    JSBIND_FUNCTION(SetSizeText);
    JSBIND_FUNCTION(SetSizeChinese);
    JSBIND_FUNCTION(SetUnderline);
    JSBIND_FUNCTION(SetSizeChar);
    JSBIND_FUNCTION(SetBold);
    JSBIND_FUNCTION(PrintFeedDot);
    JSBIND_FUNCTION(PrintQrcode);
    JSBIND_FUNCTION(Print1Dbar);
}